package com.zdkj.subway.check.controller.subwayRat.conductorDifferences.shoupiaoyuan;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zdkj.common.core.util.R;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.controller.CommonController;
import com.zdkj.subway.check.entity.Page;
import com.zdkj.subway.check.entity.SwAuCenterConductorAmountDifference;
import com.zdkj.subway.check.entity.SwAuConductorToBeChecked;
import com.zdkj.subway.check.enums.MessageEnums;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuCenterConductorAmountDifferenceMapper;
import com.zdkj.subway.check.mapper.SwAuConductorToBeCheckedMapper;
import com.zdkj.subway.check.result.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 售票员票款差异待协查
 */
@Slf4j
@RestController
@RequestMapping("/check")
public class SwAuConductorToBeCheckedController {
    @Resource
    SwAuConductorToBeCheckedMapper swAuConductorToBeCheckedMapper;
    @Resource
    SwAuCenterConductorAmountDifferenceMapper swAuCenterConductorAmountDifferenceMapper;
    @Autowired
    private CommonController commonController;
    /**
     * 获取售票员票款差异待协查列表
     * @param page
     * @param swAuConductorToBeChecked
     * @return
     */
    @RequestMapping("/getSwAuConductorToBeCheckedList")
    @ApiOperation(value = "获取售票员票款差异待协查列表", notes = "获取售票员票款差异待协查列表")
    public Page getSwAuConductorToBeCheckedList(Page page, SwAuConductorToBeChecked swAuConductorToBeChecked){
		//log.info("测试查询条件===按角色获取值=="+swAuConductorToBeChecked.getAssistCategoryRole());
        List<Map<String,Object>> res=swAuConductorToBeCheckedMapper.getSwAuConductorToBeCheckedList(swAuConductorToBeChecked);
        page.setData(res,true);
        return page;
    }

    /**
     * 售票员票款差异待协查-替換功能
     * @param ids
     * @return
     */
    @RequestMapping("/replaceSwAuConductorToBeChecked")
    @ApiOperation(value = "售票员票款差异待协查-替換功能", notes = "售票员票款差异待协查-替換功能")
    public Result replaceSwAuConductorToBeChecked(String ids){
        Result res=new Result(ResultDetailMsg.OK);
        try{
            QueryWrapper<SwAuConductorToBeChecked> queryWrapper=new QueryWrapper<>();
            queryWrapper.in("id",ids.split(","));
            //查询售票员待协查
            List<SwAuConductorToBeChecked> swAuConductorToBeCheckeds = swAuConductorToBeCheckedMapper.selectList(queryWrapper);

            for (SwAuConductorToBeChecked swAuConductorToBeChecked : swAuConductorToBeCheckeds) {
                //查询关联售票员票款差异审核
                SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(swAuConductorToBeChecked.getDifferenceId());
                if(swAuCenterConductorAmountDifference.getAuditState().equals("1")){
                    res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
                    res.setMsg("收入已审核，不能再做一键替换");
                    return res;
                }
            }
            //进行替换
            for(SwAuConductorToBeChecked swAuConductorToBeChecked:swAuConductorToBeCheckeds){
                SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = swAuCenterConductorAmountDifferenceMapper.selectById(swAuConductorToBeChecked.getDifferenceId());
                BigDecimal paid_money = swAuConductorToBeChecked.getReplyErrorReturnMoney().add(swAuConductorToBeChecked.getReplyRechargeMoney()).add(swAuConductorToBeChecked.getReplySaleMoney());
                swAuCenterConductorAmountDifference.setSaleoperatorFaretkAmount(swAuConductorToBeChecked.getReplyErrorReturnMoney());
                swAuCenterConductorAmountDifference.setSaleoperatorInvestAmount(swAuConductorToBeChecked.getReplyRechargeMoney());
                swAuCenterConductorAmountDifference.setSaleoperatorSellAmount(swAuConductorToBeChecked.getReplySaleMoney());
                swAuCenterConductorAmountDifference.setSaleoperatorPaidAmount(paid_money);
                if(swAuCenterConductorAmountDifference.getSysDataSource().equals("4")){//如果售票员票款差异的核对数据来源为“4. 售票员协查”时
                    swAuCenterConductorAmountDifference.setSysAmount(paid_money);
                    BigDecimal diffmoney = swAuCenterConductorAmountDifference.getPaidAmount().subtract(paid_money).subtract(swAuCenterConductorAmountDifference.getPassengerWorkAmount()).subtract(swAuCenterConductorAmountDifference.getMarketTicketAmount()).subtract(swAuCenterConductorAmountDifference.getSingleTicketAmount()).subtract(swAuCenterConductorAmountDifference.getEmergencyAmount());
                    swAuCenterConductorAmountDifference.setDifferenceAmount(diffmoney);
                }
                //修改售票员票款差异审核表
                swAuCenterConductorAmountDifferenceMapper.updateById(swAuCenterConductorAmountDifference);

                //更新售票员待协查表
                swAuConductorToBeChecked.setReplaceStatus("1");
                swAuConductorToBeChecked.setReplaceTime(new Date());
                swAuConductorToBeCheckedMapper.updateById(swAuConductorToBeChecked);
            }

        }catch (Exception e){
            log.error("{}",e);
            res.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            res.setMsg("替换失败");
        }
        return res;
    }


    /**
     * 售票员票款差异待协查-下发
     * @param param
     * @return
     */
    @RequestMapping("/sendStatusSwAuConductorToBeChecked")
    @ApiOperation(value = "售票员票款差异待协查-下发", notes = "售票员票款差异待协查-下发")
    @Transactional(rollbackFor = Exception.class)
    public Result sendStatusSwAuConductorToBeChecked(@RequestBody Map<String,Object> param){
        PigxUser user = SecurityUtils.getUser();
        Result result=new Result(ResultDetailMsg.OK);
        try {
            String ids = String.valueOf(param.get("ids"));
			String assistCategory = String.valueOf(param.get("assistCategory"));
			 for (String id : ids.split(",")) {
                SwAuConductorToBeChecked oldSwAuConductorToBeChecked = swAuConductorToBeCheckedMapper.selectById(Integer.parseInt(id));
				//SwAuConductorToBeChecked swAuConductorToBeChecked = new SwAuConductorToBeChecked();
				String oldAssistCategory = oldSwAuConductorToBeChecked.getAssistCategory();//增加二次下发的验证
				 
				 //1.机电  2：客运  3.两个
				if("1".equals(assistCategory)){	
				  if(oldAssistCategory.equals("0")){ //非二次下发
				     //机电协查状态
				       oldSwAuConductorToBeChecked.setAssistState("2");
					}
				}else if("2".equals(assistCategory)){	
				  if(oldAssistCategory.equals("0")){
					 //客运协查状态
				   oldSwAuConductorToBeChecked.setAssistState("2");
				  }
				  oldSwAuConductorToBeChecked.setKyAssistInvestStatus("2");
				
				}else if("3".equals(assistCategory)){	
					 //机电协查状态
				   oldSwAuConductorToBeChecked.setAssistState("2");
					//客运协查状态
				   oldSwAuConductorToBeChecked.setKyAssistInvestStatus("2");
				}
				 if(oldAssistCategory.equals("0")){ //非二次下发
					oldSwAuConductorToBeChecked.setAssistCategory(assistCategory);
				 }else{
					oldSwAuConductorToBeChecked.setAssistCategory("3");//二次下发的统一改为3，两个部门同时下发
				 }
				 oldSwAuConductorToBeChecked.setAssistTime(new Date());
                 oldSwAuConductorToBeChecked.setSendPersonCode(user.getUserCode());//下发人工号
                 oldSwAuConductorToBeChecked.setSendPersonName(user.getNikeName());//下发人				
				 swAuConductorToBeCheckedMapper.updateById(oldSwAuConductorToBeChecked);

			 }
			  //走机电
            if(param.get("jdType")!=null){
                Map<String,Object> jdParam = new HashMap<>(param);
                jdParam.put("type",param.get("jdType").toString());
                jdParam.put("roleCode", MessageEnums.SBBJSRY_ROLE_CODE.getCode());
                commonController.innerBatch(jdParam);
            }
            //走客运
            if(param.get("kyType")!=null){
                Map<String,Object> kyParam = new HashMap<>(param);
                kyParam.put("type",param.get("kyType").toString());
                commonController.innerBatch(kyParam);
            }
			/*  20250825 适应二次下发调整
			String assistCategory = String.valueOf(param.get("assistCategory"));
            UpdateWrapper<SwAuConductorToBeChecked> updateWrapper=new UpdateWrapper<>();
            updateWrapper.in("id",ids.split(","));
            SwAuConductorToBeChecked swAuConductorToBeChecked = new SwAuConductorToBeChecked();
            swAuConductorToBeChecked.setAssistCategory(assistCategory);
			 //1.机电  2：客运  3.两个
			if("1".equals(assistCategory)){	
			  //机电协查状态
               swAuConductorToBeChecked.setAssistState("2");
			}else if("2".equals(assistCategory)){	
				 //客运协查状态
			   swAuConductorToBeChecked.setAssistState("2");
               swAuConductorToBeChecked.setKyAssistInvestStatus("2");
			
			}else if("3".equals(assistCategory)){	
				 //机电协查状态
               swAuConductorToBeChecked.setAssistState("2");
			    //客运协查状态
               swAuConductorToBeChecked.setKyAssistInvestStatus("2");
			}
            
            swAuConductorToBeChecked.setAssistTime(new Date());
            swAuConductorToBeChecked.setSendPersonCode(user.getUserCode());//下发人工号
            swAuConductorToBeChecked.setSendPersonName(user.getNikeName());//下发人
            swAuConductorToBeCheckedMapper.update(swAuConductorToBeChecked,updateWrapper);
            //走机电
            if(param.get("jdType")!=null){
                Map<String,Object> jdParam = new HashMap<>(param);
                jdParam.put("type",param.get("jdType").toString());
                jdParam.put("roleCode", MessageEnums.SBBJSRY_ROLE_CODE.getCode());
                commonController.innerBatch(jdParam);
            }
            //走客运
            if(param.get("kyType")!=null){
                Map<String,Object> kyParam = new HashMap<>(param);
                kyParam.put("type",param.get("kyType").toString());
                commonController.innerBatch(kyParam);
            }*/
        }catch (Exception e){
            log.error("{}",e);
            result.setResult(ResultDetailMsg.CHECK_UPDATE_ERROR);
            result.setMsg("下发失败！");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 批量删除售票员票款未下发的
     * @param idList
     * @return
     */
    @DeleteMapping("/batchSPYDel")
    @ApiOperation(value = "通过id批量删除售票员票款未下发的", notes = "通过id批量删除售票员票款未下发的")
    @Transactional(rollbackFor = Exception.class)
    public R batchRemoveSPYById(@RequestBody List<Integer> idList) {
        List<SwAuConductorToBeChecked> list = swAuConductorToBeCheckedMapper.selectList(new QueryWrapper<SwAuConductorToBeChecked>().lambda().in(SwAuConductorToBeChecked::getId, idList));
        //删除之前需要改变审核表的加入协查状态为未加入 '0'
        List<Integer> integerList = list.stream().map(SwAuConductorToBeChecked::getDifferenceId).collect(Collectors.toList());
        SwAuCenterConductorAmountDifference swAuCenterConductorAmountDifference = new SwAuCenterConductorAmountDifference();
        swAuCenterConductorAmountDifference.setIsAddAssist("0");//是否加入协查
        swAuCenterConductorAmountDifference.setAssitAuditSate("0");//协查状态
        UpdateWrapper<SwAuCenterConductorAmountDifference> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id",integerList);
        swAuCenterConductorAmountDifferenceMapper.update(swAuCenterConductorAmountDifference,updateWrapper);
        //执行删除
        return R.ok(swAuConductorToBeCheckedMapper.deleteBatchIds(idList));
    }

}
